package LeetCode;


import java.util.ArrayList;
import java.util.List;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName interview
 * @Description: TODO
 * @date ${DAT}15:29
 */
public class LeetCode77 {

    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> combine(int n, int k) {
        if (n == 0){
            return res;
        }
        List<Integer> list = new ArrayList<>();
        getResult2(n,k,1,list);
        return res;
    }

    public void getResult(int n, int k, int start, List<Integer> list){
        if (list.size() == k){
            res.add(new ArrayList<>(list));
            return;
        }
        for (int i = start; i <= n - (k - list.size()) + 1; i++){
            list.add(i);
            getResult(n,k,i + 1,list);
            list.remove(list.size() - 1);
        }
    }

    // 这里就是取了不放回的情况
    public void getResult2(int n, int k, int start, List<Integer> list){
        if (list.size() == k){
            res.add(new ArrayList<>(list));
            return;
        }
        int index = n - (k - list.size());
        // 这里index的作用是: 当list.size()为0时这时就说明这里分配的是组合的开头，只能是1~3
        // 当list.size()为1是，说明这个时候是分配的是组合的第二个数，右边界就是n
        for (int i = start; i <= index + 1; i++){// 本题的要求 按顺序来进行排列，所以不能进行全排列
            list.add(i);
            getResult2(n,k,i + 1,list);
            list.remove(list.size() - 1);
        }
    }

    public static void main(String[] args) {
        System.out.println(new LeetCode77().combine3(4, 2).toString());
    }

    public List<List<Integer>> combine3(int n, int k) {
        if (k == 0){
            return new ArrayList<>();
        }
        dfs(n,k,1,new ArrayList<>());
        return res;
    }

    private void dfs(int n, int k, int start, List<Integer> list) {
        if (list.size() == k){
            res.add(new ArrayList<>(list));
            return;
        }

        for (int i = start; i <= n - (k - list.size()) + 1; i++){
            list.add(i);
            dfs(n,k,i + 1,list);
            list.remove(list.size() - 1);
        }
    }
}
